package com.invoicing.controller;

import com.invoicing.MainController;
import com.invoicing.Service.CommodityService;
import com.invoicing.Service.OrderService;
import com.invoicing.Service.OrderitemService;
import com.invoicing.Service.TypeService;
import com.invoicing.entity.Commodity;
import com.invoicing.entity.CommodityData;
import com.invoicing.entity.Order;
import com.invoicing.entity.OrderItem;
import com.invoicing.view.MenuView;
import de.felixroske.jfxsupport.FXMLController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


import java.awt.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import  java.util.List;

@FXMLController
public class SellController implements Initializable {


    Commodity commodity = new Commodity();
    String typeString = " ";
    int num = 0;//序号
    private  float Whole_Price = 0;//总价
    private ObservableList<CommodityData> data = FXCollections.observableArrayList();
    int flag  = 0;//重复标志
    private List<OrderItem> orderItems = new ArrayList<OrderItem>();//销售物品列
    java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");

    @Autowired
    private CommodityService commodityService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderitemService orderitemService;

    @FXML
    private TextField id;

    @FXML
    private TableView table;

    @FXML
    private TableColumn order_num;

    @FXML
    private TableColumn price;

    @FXML
    private TableColumn name;

    @FXML
    private TableColumn after_price;

    @FXML
    private TableColumn discount;

    @FXML
    private TableColumn sell_count;

    @FXML
    private TableColumn little_total;

    @FXML
    private Label total_price;

    @FXML
    private Label show_total;

    @FXML
    private Label time;

    @FXML
    private TextField actual_price;

    @FXML
    private Label change;


    public void initialize(URL location, ResourceBundle resources) {

        order_num.setCellValueFactory(new PropertyValueFactory<CommodityData, Integer>("num"));
        price.setCellValueFactory(new PropertyValueFactory<CommodityData, Float>("price"));
        name.setCellValueFactory(new PropertyValueFactory<CommodityData, String>("name"));
        after_price.setCellValueFactory(new PropertyValueFactory<CommodityData, Float>("sell_price"));
        discount.setCellValueFactory(new PropertyValueFactory<CommodityData, Float>("discount"));
        sell_count.setCellValueFactory(new PropertyValueFactory<CommodityData, Integer>("sell_count"));
        little_total.setCellValueFactory(new PropertyValueFactory<CommodityData, Float>("sell_total"));
        time.setText(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));

    }
    //private List<CommodityData> commodityDataList = new ArrayList<CommodityData>();

    @FXML
    private void setSure(){

        if(id.getText().length()==0){

            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setContentText("请输入商品编号");
            alert.show();
        }//未输入
        else{
            if(commodityService.findCommodity(Integer.parseInt(id.getText()))==null){
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setContentText("该商品不存在，请从新输入");
                alert.show();
                id.clear();
            }
            else if(commodityService.findCommodity(Integer.parseInt(id.getText())).getStock()==0){
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setContentText("商品已无库存，请从新输入");
                alert.show();
                id.clear();
            }
            else if(commodityService.findCommodity(Integer.parseInt(id.getText())).getPrice()==0){
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setContentText("商品尚未计划出售，请从新输入");
                alert.show();
                id.clear();
            }
            else{//商品存在
                flag = 0;
                for(int i=0;i<data.size();i++){
                    if(Integer.parseInt(id.getText())==data.get(i).getId()){//商品已经在售

                        flag = 1;
                        data.get(i).setSell_count(data.get(i).getSell_count()+1);
                        data.get(i).setSell_total(Float.parseFloat(df.format(data.get(i).getSell_total()+data.get(i).getSell_price())));
                        Whole_Price = Whole_Price+data.get(i).getSell_price();//更新总价
                        table.refresh();
                        id.clear();
                        break;

                    }
                }
                if(flag==0){
                    num = num +1;
                    commodity = commodityService.findCommodity(Integer.parseInt(id.getText()));
                    typeString = typeService.findById(commodity.getTypeId()).getTypeName();
                    Float f = commodity.getPrice()*commodity.getDiscount();
                    CommodityData commodityData = new CommodityData(commodity,num,typeString,0,0,f,1);
                    Whole_Price = Whole_Price+f;//更新总价
                    data.add(commodityData);
                    commodityData.getSell_price();
                    table.setItems(data);
                    id.clear();
                }
            }
        }
        total_price.setText(df.format(Whole_Price)+"");
        show_total.setText(df.format(Whole_Price)+"");


    }
    @FXML
    private void setSettle(){
        if(actual_price.getText().length()==0){//未填写实收款
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setContentText("请填写实收款额");
            alert.show();
        }
        else if(Float.parseFloat(actual_price.getText())<Float.parseFloat(total_price.getText())){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setContentText("实收款不足应收款");
            actual_price.clear();
            alert.show();
        }
        else {
            id.setEditable(false);
            actual_price.setEditable(false);//敲定订单
            float ch = Float.parseFloat(actual_price.getText())-Float.parseFloat(total_price.getText());
            if(ch<1){
                change.setText("0"+df.format(ch)+"");
            }
            else change.setText(df.format(ch)+"");
        }
    }

    @FXML
    private void setFinish(){
        if(change.getText().length()==0){//未结账
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setContentText("请先结账");
            alert.show();
        }
        else if(change.getText().length()!=0){//存单

            Order order = new Order();
            Date date = new Date();
            order.setOrderPrice(Float.parseFloat(total_price.getText()));
            order.setOrderTime(date);
            orderService.insert(order);

            for(int i=0;i<data.size();i++){
                OrderItem orderItem = new OrderItem();

                orderItem.setId(data.get(i).getId());
                orderItem.setOrderId(orderService.selectRecent().getOrderId());
                orderItem.setOrderNum(i+1);//序号
                orderItem.setOrderUnivalence(data.get(i).getSell_price());
                orderItem.setOrderCount(data.get(i).getSell_count());

                commodityService.updateStock(data.get(i).getId(),data.get(i).getStock()-data.get(i).getSell_count());

                orderItems.add(orderItem);
            }
            System.out.println("xx零售店");
            System.out.println("============================");
            System.out.println("序        商品名称");
            System.out.println("商品编号 售价*数量  金额");
            int total_count = 0;
            float total_cost = 0;
            for(int i= 0 ;i < data.size();i++){
                float price = data.get(i).getSell_price();
                int count = data.get(i).getSell_count();
                System.out.println(i+1+">"+data.get(i).getName());
                System.out.println(data.get(i).getId()+"   "+price+"*"+count+"="+price*count);
                total_count+= count;
                total_cost+= price*count;
            }
            System.out.println("----------------------------");
            System.out.println("共"+data.size()+"项"+"    "+"数量:"+total_count);
            System.out.println("合计： "+ df.format(total_cost));
            System.out.println("收款金额： "+df.format(Float.parseFloat(actual_price.getText())));
            System.out.println("找款金额： "+df.format((Float.parseFloat(actual_price.getText())-Float.parseFloat(total_price.getText()))));
            System.out.println("订单编号为： "+orderService.selectRecent().getOrderId());
            System.out.println("=============================");


            orderitemService.insert(orderItems);//插入销售记录

            id.setEditable(true);//存单后初始化
            actual_price.setEditable(true);
            actual_price.clear();
            id.clear();
            data.clear();
            table.setItems(data);
            num = 0;
            Whole_Price = 0;
            orderItems.clear();
            show_total.setText(null);
            total_price.setText(null);
            change.setText(null);
        }

    }







    @FXML
    private void setBack(){
        MainController.showView(MenuView.class);

        actual_price.clear();
        id.clear();
        data.clear();
        table.setItems(data);
        num = 0;
        Whole_Price = 0;
        orderItems.clear();
        show_total.setText(null);
        total_price.setText(null);
        change.setText(null);
    }
}
